package com.ermao.mymes.handler.service.deduplication;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ermao.mymes.common.constant.MyMesConstant;
import com.ermao.mymes.handler.domain.DeduplicationParam;
import com.ermao.mymes.common.domain.TaskInfo;
import com.ermao.mymes.common.enums.DeduplicationType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Ermao
 * Date: 2022/5/9 14:44
 */
@Service
public class DeduplicationRuleService {

	public static final String DEDUPLICATION_RULE_KEY = "deduplication";

	@ApolloConfig("dev.mymes")
	private Config config;

	@Autowired
	private DeduplicationHolder deduplicationHolder;

	public void duplication(TaskInfo taskInfo) {
		// 配置样例：{"deduplication_10":{"num":1,"time":300},"deduplication_20":{"num":5}}
		String deduplicationConfig = config.getProperty(DEDUPLICATION_RULE_KEY, MyMesConstant.APOLLO_DEFAULT_VALUE_JSON_OBJECT);

		// 去重
		List<Integer> deduplicationList = DeduplicationType.getDeduplicationList();
		for (Integer deduplicationType : deduplicationList) {
			// 从 holder 中根据 deduplicationType 获取 builder，再用 builder 构造 deduplicationParam
			DeduplicationParam deduplicationParam = deduplicationHolder.selectBuilder(deduplicationType).build(deduplicationConfig, taskInfo);
			if (deduplicationParam != null) {
				// 如果成功构建去重参数，则调用对应的去重服务来对去重参数进行去重（修改 TaskInfo）
				deduplicationHolder.selectService(deduplicationType).deduplication(deduplicationParam);
			}
		}
	}
}
